package com.design.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.design.reggie.common.Result;
import com.design.reggie.dto.DishDto;
import com.design.reggie.entity.Category;
import com.design.reggie.entity.Dish;
import com.design.reggie.entity.DishFlavor;
import com.design.reggie.service.CategoryService;
import com.design.reggie.service.DishFlavorService;
import com.design.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@RequestMapping("/dish")
@RestController
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    CategoryService categoryService;

    @GetMapping("/page")
    public Result<Page<DishDto>> page(int page, int pageSize, String name) {
        // 分页构造器
        Page<Dish> dishPage = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        // 条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        // 注意这边要判断name是否为空
        queryWrapper.like(!StringUtils.isEmpty(name), Dish::getName, name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);

        // 分页查询，并返回结果
        dishService.page(dishPage, queryWrapper);

        // 对象拷贝,BeanUtils.copyProperties用来拷贝Bean的属性值
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");
        List<Dish> records = dishPage.getRecords();

        // for循环实现
        // 如果要用List的add方法，那么必须new出List，而不能 List<DishDto> list=null；
        List<DishDto> list = new ArrayList<>();
        for (Dish record : records) {
            DishDto dishDto = new DishDto();
            // 拷贝属性
            BeanUtils.copyProperties(record, dishDto);
            // 根据id获取分类数据
            Category category = categoryService.getById(record.getCategoryId());
            // 获取分类名
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);

            list.add(dishDto);
        }

        // stream流的方式实现
//        List<DishDto> list = null;
//        list = records.stream().map((item) -> {
//            DishDto dishDto = new DishDto();
//            BeanUtils.copyProperties(item, dishDto);
//
//            Long categoryId = item.getCategoryId();
//            Category category = categoryService.getById(categoryId);
//            // 根据分类id获取分类名
//            String categoryName = category.getName();
//            dishDto.setCategoryName(categoryName);
//            return dishDto;
//
//        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);

        return Result.success(dishDtoPage);

    }

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public Result<String> addDish(@RequestBody DishDto dishDto) {
//        dishService.save(dish);
        // 自定义函数，在保存菜品的同时保存菜品口味
        dishService.addWithFlavors(dishDto);

        return Result.success("新增菜品成功");
    }

    /**
     * 更新菜品
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public Result<String> update(@RequestBody DishDto dishDto) {
//        dishService.save(dish);
        // 自定义函数，在保存菜品的同时保存菜品口味
        dishService.updateWithFlavors(dishDto);

        return Result.success("修改菜品信息成功");
    }

    /**
     * 根据id查询菜品回显给修改页面
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<DishDto> updateList(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavors(id);
        return Result.success(dishDto);
    }

    /**
     * 修改菜品状态（启售，禁售）
     *
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public Result<String> editStatus(@PathVariable int status, String ids) {
        String[] split = ids.split(",");
        for (String s : split) {
            Dish dish = dishService.getById(s);
            dish.setStatus(status);
            dishService.updateById(dish);
        }

        return Result.success("修改菜品状态成功");
    }

    /**
     * 删除菜品
     * @param ids
     * @return
     */
    @DeleteMapping
    public Result<String> delete(String ids) {

        dishService.deleteWithFlavors(ids);
        return Result.success("删除菜品成功");
    }

    /**
     * 查询分类下的菜品（在售的）
     * @param categoryId
     * @param status
     * @return
     */
    @GetMapping("/list")
    public Result<List<DishDto>> list(long categoryId, Integer status) {
        // 首先查出符合条件的 Dish
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getCategoryId, categoryId);
        queryWrapper.eq(status != null, Dish::getStatus, status);
        List<Dish> list = dishService.list(queryWrapper);

        // 添加口味数据到 DishDto
        List<DishDto> dishDtoList = new ArrayList<>();
        for (Dish dish : list) {
            DishDto dishDto = new DishDto();
            Long dishId = dish.getId();
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
            List<DishFlavor> flavors = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
            BeanUtils.copyProperties(dish, dishDto);
            dishDto.setFlavors(flavors);
            dishDtoList.add(dishDto);
        }

        // 最后返回的就是DishDto
        return Result.success(dishDtoList);
    }


}
